"""
    Easy way to include the google analytics script code.
    Usage:
        Configure your CACHE_MIDDLEWARE_KEY_PREFIX and your cache
        {% load urchin %}
        Just put before the </body> of your page {% urchin "your-urchin-code" %}

        You can force the application to get your urchin code from the settings using
        settings as the urchin code. The application will try to find a setting.URCHIN_CODE
"""
# Author : aaloy - Adapted from http://www.djangosnippets.org/snippets/457/ by blinks
# to add cache key and include the new analytics code.
from django import template
from django.core.cache import cache
from django.conf import settings
register = template.Library()

def urchin (uacct):
    if uacct == "settings":
        uacct = settings.URCHIN_CODE
    cache_key = '%sanalytics_trespams'%settings.CACHE_MIDDLEWARE_KEY_PREFIX
    urchin_code = cache.get(cache_key)
    if urchin_code == None:
        if not settings.DEBUG:

            urchin_code=u"""
            <script type="text/javascript">
              var _gaq = _gaq || [];
              _gaq.push(['_setAccount', '%(uacct)s']);
              _gaq.push(['_trackPageview']);
              _gaq.push(['_trackPageLoadTime']);
              (function() {
                var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
                ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
                var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
              })();

            </script>""" % {'uacct':uacct}
            cache.set(cache_key, urchin_code, 86400)
        else:
            urchin_code= u"<!-- aqui ira el codigo de analytics en produccion %(uacct)s -->"  % {'uacct':uacct}
    return urchin_code
register.simple_tag(urchin)
